package com.gzy.rpsm.property.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzy.rpsm.property.mapper.UserMapper;
import com.gzy.rpsm.property.pojo.PageResult;
import com.gzy.rpsm.property.pojo.UnpaidOwner;
import com.gzy.rpsm.property.pojo.User;
import com.gzy.rpsm.property.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(String account, String password){
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        User user = userMapper.queryByAccountAndPassword(account, password);
        if(user== null){
            return null;
        }
        String token = TokenUtil.generateToken(user.getUserid());// 登录成功，生成token
        user.setToken(token);// 将设置到user的token字段中
        return user;
    }

    @Override
//新增 account 可能触发唯一索引的异常
    public int insertUser(User user) throws DuplicateKeyException, Exception {
        int result = -1;
        // TODO, 应该是返回新增的user的id
        //int a = 1/0;
        result = userMapper.insertUser(user);
        return result;
    }

    @Override
    public PageResult<User> pageOfOwner(int current, int size) {
        PageHelper.startPage(current,size);
        Page<User> page = userMapper.owners();
        return PageResult.restPage(page);
    }

    @Override
    public int changeUserStatus(User user) {
        return userMapper.changeUserStatus(user);
    }

    @Override
    public User queryById(int id) {
        return userMapper.queryById(id);
    }

    @Override
    public PageResult<UnpaidOwner> pageOfUnpaidOwnerList(Integer current, Integer size, Integer typeId) {
        PageHelper.startPage(current, size);
        Page<UnpaidOwner> page = userMapper.unpaidOwnerList(typeId);
        return PageResult.restPage(page);
    }
}